// pages/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //储存用户的订单
    list: '',
    all: '',
    lists: '',
    //用于判断是否存在订单
    goodsstat: true,
    //判断传递进来参数
    orderStatus: '',
    show: 1,
    orderPric: [],
    selectedIndex: ''
  },

  //调用api获取用户的订单
  getorder: function () {
    var that = this;
    var app = getApp();
    var id = app.globalData.userInfo.wxUserId;
    wx.request({
      url: `https://199shq.com/api/orders/wxUser/${id}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        // console.log('获取用户的订单')
        // console.log(res.data.data);
        var list = res.data.data;
        var classifiedArray = [];

        var obj = {};
        for (var i = 0; i < list.length; i++) {
          var item = list[i];
          var id = item.identity;
          // console.log(obj)
          // console.log(id)
          if (obj[id]) {
            obj[id].push(item);
            // console.log(obj[id])
          } else {
            obj[id] = [item];
          }
        }
        for (var key in obj) {
          classifiedArray.push(obj[key]);
        }
        var orderPricee = {}
        for (let i = 0; i < classifiedArray.length; i++) {
          // console.log(classifiedArray[i])

          if (classifiedArray[i].length >= 2) {
            var classifiedArrays = []
            classifiedArrays = classifiedArray[i]

            var orderPrices = 0
            for (let j = 0; j < classifiedArrays.length; j++) {
              orderPrices += classifiedArrays[j].orderPrice
              // console.log(orderPrices)
            }
            // console.log('进入')
            orderPricee[i] = orderPrices

          }
        }
        that.setData({
          orderPric: orderPricee,
          // orderStatus:5
        })
        if (res.data.data.length == 0) {
          that.setData({
            allgoods: 0
          })
        }
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            list: classifiedArray,
            lists: classifiedArray,

            all: res.data.data
          })
          // console.log(that.data.all.length);
          if (that.data.all.length == 0) {
            that.setData({
              goodsstat: true
            })
          } else {
            that.setData({
              goodsstat: false
            })
          }
          that.getstat();
        }
      }
    })

  },
  quanbu: function () {
    const lists = this.data.lists
    console.log('进入')
    // lists = 
    this.setData({
      list: lists,
      selectedIndex: 0,
      orderStatus: 0,
    })
    if (this.data.list.length >0) {
      this.setData({
        goodsstat: false,
      })
    }else{
      this.setData({
        goodsstat: true,
      })
    }
    console.log(this.data.list.length)
  },
  //定义函数跳转到订单详情页面
  goto: function (e) {
    var item = e.currentTarget.dataset.item;
    console.log('点击查看详情跳转到 详情订单的页面', item);
    console.log(item);
    var app = getApp();
    app.globalData.addid = item;
    console.log(app.globalData.addid);
    wx.navigateTo({
      url: '/pages/orderRess/orderRess'
    });
  },
  // 联系商家
  delorder1() {
    // 如果用户已授权登录，则跳转到对应页面
    wx.navigateTo({
      url: '/pages/service/service'
    });
  },
  // 立即评价
  evaluate: function (e) {
    var item = e.currentTarget.dataset.item;
    console.log("评价详情页面")
    console.log(item);
    var app = getApp();
    app.globalData.addid = item;
    wx.navigateTo({
      url: '/pages/orderRess/orderRess'
    });
  },

  //当用户点击了取消订单时在数据库逻辑删除
  delorder: function (e) {
    var item = e.currentTarget.dataset.item;
    console.log(item);
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否取消订单',
      success(res) {
        if (res.confirm) {
          for (var i = 0; i < item.length; i++) {
            wx.request({
              url: `https://199shq.com/api/orders/delete/${item[i].id}`,
              method: 'PUT',
              header: {
                'Content-Type': 'application/json',
                'token': wx.getStorageSync('token')
              },
              success: function (res) {
                console.log(res.data.data);
                var list = res.data.data;
                if (list == null) {
                  var toastText = '数据获取失败';
                  wx.showToast({
                    title: 'toastText',
                    icon: '',
                    duration: 2000
                  });
                } else {
                  wx.showToast({
                    title: `${res.data.data}`,
                    icon: 'none',
                    duration: 2000
                  });
                  that.getorder();
                }
              }
            })
          }
        } else if (res.cancel) {
          return false
        }
      }
    })
  },
  showTooltip(e) {
    console.log(e.currentTarget.dataset.shippingmethod)
    if (e.currentTarget.dataset.shippingmethod == '院内自取') {
      // console.log('进入')
      wx.showModal({
        title: '提示',
        content: '今日订的餐将明日领取，自取地址为综合楼一楼西药房对面临床营养服务中心',
        success(res) {
          console.log(res)
          if (res.confirm) {
            // 用户点击了确定按钮
          } else if (res.cancel) {
            // 用户点击了取消按钮
            console.log('用户点击了取消');
            // 这里可以添加点击取消后的逻辑代码，比如关闭弹窗，不做其他操作等
          }

        },
        fail(err) {
          // 调用失败的回调函数
          console.error('弹窗调用失败:', err);
        }
      });
    } else {

    }
  },
  //当用户点击了确认收货后将订单改为已完成订单，并且判断该订单是否存在邀请人
  //如果存在邀请人则将佣金处理
  delorder2(e) {
    var that = this;
    var item = e.currentTarget.dataset.item;
    console.log(item);
    // 将订单修改为已完成订单
    wx.showModal({
      title: '提示',
      content: '是否确认收货',
      success(res) {
        if (res.confirm) {
          for (var i = 0; i < item.length; i++) {
            wx.request({
              url: `https://199shq.com/api/orders/status4/${item[i].id}`,
              method: 'PUT',
              header: {
                'Content-Type': 'application/json',
                'token': wx.getStorageSync('token')
              },
              success: function (res) {
                // 请求成功处理逻辑
                wx.showToast({
                  title: '完成订单',
                  icon: 'success',
                  duration: 2000
                });
                console.log('完成订单');
                // 根据返回的结果进行相应的操作
                console.log(item[i]);
                //当执行成功后，重新刷新待收货页面
                if (res.data.code == 200) {
                  that.getorder();
                  //判断该订单是否存在邀请人
                  // if (item[i].inviteId != null) {
                  //   //获取该订单商品的佣金

                  //   //定义一个商品佣金用来保存商品佣金,并且判断该商品是否存在佣金
                  //   wx.request({
                  //     url: `https://www.jingtengyiliao.com/api/orders/details/${item[i].id}`,
                  //     method: 'GET',
                  //     header: {
                  //       'Content-Type': 'application/json',
                  //       'token': wx.getStorageSync('token')
                  //     },
                  //     success: function (res) {
                  //       console.log(res.data.data);
                  //       var list = res.data.data;
                  //       if (list == null) {
                  //         var toastText = '数据获取失败';
                  //         wx.showToast({
                  //           title: 'toastText',
                  //           icon: '',
                  //           duration: 2000
                  //         });
                  //       } else {

                  //       }
                  //       wx.request({
                  //         url: `https://www.jingtengyiliao.com/api/tproduct/${res.data.data.goodsId}`,
                  //         method: 'GET',
                  //         header: {
                  //           'Content-Type': 'application/json',
                  //           'token': wx.getStorageSync('token')
                  //         },
                  //         success: function (res) {
                  //           console.log(res.data.data.commission);
                  //           var list = res.data.data;
                  //           console.log("查询所有商品,是否存在邀请人")
                  //           console.log(list);
                  //           if (list == null) {
                  //             var toastText = '数据获取失败';
                  //             wx.showToast({
                  //               title: 'toastText',
                  //               icon: '',
                  //               duration: 2000
                  //             });
                  //           } else {
                  //             //商品存在佣金，则调用api给邀请人添加佣金
                  //             if (res.data.data.commission != null) {
                  //               var goodcommission = res.data.data.commission;
                  //               console.log("该订单存在邀请人");
                  //               //首先查出该订单邀请人的id
                  //               //通过订单邀请人的id查询出该订单邀请人佣金金额
                  //               wx.request({
                  //                 url: `https://www.jingtengyiliao.com/api/distribution/selectDistributionAmountByWxUserId/${item[i].inviteId}`,
                  //                 method: 'GET',
                  //                 header: {
                  //                   'Content-Type': 'application/json',
                  //                   'token': wx.getStorageSync('token')
                  //                 },
                  //                 success: function (res) {
                  //                   console.log(res.data.data.distributionAmount);
                  //                   //获取修改后的金额commission
                  //                   var commission = res.data.data.distributionAmount + goodcommission;
                  //                   //调用修改api进行修改
                  //                   console.log('到账')
                  //                   wx.request({
                  //                     url: `https://www.jingtengyiliao.com/api/distribution?money=${commission}&wxUserId=${item[i].inviteId}`,
                  //                     method: 'PUT',
                  //                     header: {
                  //                       'Content-Type': 'application/json',
                  //                       'token': wx.getStorageSync('token')
                  //                     },
                  //                     success: function (res) {
                  //                       console.log(res.data);
                  //                     }
                  //                   })
                  //                 }
                  //               })
                  //             }
                  //           }
                  //         }
                  //       })
                  //     }
                  //   })
                  // } else {
                  //   console.log("该订单不存在邀请人");
                  // }
                  that.getorder();
                }
              },
              fail: function (error) {
                wx.showToast({
                  title: '确认收货失败',
                  icon: 'none',
                  duration: 2000
                });
                // 请求失败处理逻辑
                console.error('确认收货失败', error);
              }
            });
          }
        }
      }
    })

  },

  //显示待付款的订单
  payment: function () {
    console.log(this.data.all);
    var that = this;
    var arr = [];
    var identityMap = {}; // 存储已经存在的 identity 值
    // for(var i = 0; i < that.data.all.length; i++){
    //   if(that.data.all[i].orderStatus == 0) {
    //     arr.push(that.data.all[i]);
    //   }
    // }
    for (var i = 0; i < that.data.all.length; i++) {
      if (that.data.all[i].orderStatus == 0) {
        var identity = that.data.all[i].identity; // 假设 identity 是用来标识对象的唯一值
        if (!identityMap[identity]) {
          var nestedArray = that.data.all[i];
          var nestedArr = [];
          nestedArr.push(nestedArray);
          arr.push(nestedArr);
          identityMap[identity] = arr.length - 1; // 将 identity 值与索引关联起来
        } else {
          // 如果已经存在相同 identity 值的数组，则直接将对象添加到对应的数组中
          arr[identityMap[identity]].push(that.data.all[i]);
        }
      }
    }


    console.log("待付款信息")
    console.log(arr)
    this.setData({
      list: arr,
      selectedIndex: 1,
      orderStatus: 1,
    })
    if (this.data.list.length == 0) {
      that.setData({
        goodsstat: true
      })
    } else {
      that.setData({
        goodsstat: false
      })
    }
  },

  //显示代发货的订单
  shipments: function () {
    var that = this;
    var arr = [];
    var identityMap = {}; // 存储已经存在的 identity 值

    // for(var i = 0; i < that.data.all.length; i++){
    //   if(that.data.all[i].orderStatus == 2) {
    //     arr.push(that.data.all[i]);
    //   }
    // }

    for (var i = 0; i < that.data.all.length; i++) {
      if (that.data.all[i].orderStatus == 2 || that.data.all[i].orderStatus == 1) {
        var identity = that.data.all[i].identity; // 假设 identity 是用来标识对象的唯一值
        if (!identityMap[identity]) {
          var nestedArray = that.data.all[i];
          var nestedArr = [];
          nestedArr.push(nestedArray);
          arr.push(nestedArr);
          identityMap[identity] = arr.length - 1; // 将 identity 值与索引关联起来
        } else {
          // 如果已经存在相同 identity 值的数组，则直接将对象添加到对应的数组中
          arr[identityMap[identity]].push(that.data.all[i]);
        }
      }
    }
    console.log("待发货")
    console.log(arr)
    this.setData({
      list: arr,
      selectedIndex: 2,
      orderStatus: 2,
    })
    if (this.data.list.length == 0) {
      that.setData({
        goodsstat: true
      })
    } else {
      that.setData({
        goodsstat: false
      })
    }
  },


  // endInter: function() {
  // var that = this;
  // clearInterval(that.data.inter);
  // },
  //显示待收货订单
  receipt: function () {
    var that = this;
    var arr = [];
    var identityMap = {}; // 存储已经存在的 identity 值
    // for(var i = 0; i < that.data.all.length; i++){
    //   if(that.data.all[i].orderStatus == 3) {
    //     arr.push(that.data.all[i]);
    //   }
    // }
    for (var i = 0; i < that.data.all.length; i++) {
      if (that.data.all[i].orderStatus == 3) {
        var identity = that.data.all[i].identity; // 假设 identity 是用来标识对象的唯一值
        if (!identityMap[identity]) {
          var nestedArray = that.data.all[i];
          var nestedArr = [];
          nestedArr.push(nestedArray);
          arr.push(nestedArr);
          identityMap[identity] = arr.length - 1; // 将 identity 值与索引关联起来
        } else {
          // 如果已经存在相同 identity 值的数组，则直接将对象添加到对应的数组中
          arr[identityMap[identity]].push(that.data.all[i]);
        }
      }
    }

    this.setData({
      list: arr,
      selectedIndex: 3,
      orderStatus: 3,
    })
    console.log(arr)
    if (this.data.list.length == 0) {
      that.setData({
        goodsstat: true
      })
    } else {
      that.setData({
        goodsstat: false
      })
    }
  },


  //显示已完成订单
  ovre: function () {
    var that = this;
    var arr = [];
    var identityMap = {}; // 存储已经存在的 identity 值
    // for(var i = 0; i < that.data.all.length; i++){
    //   if(that.data.all[i].orderStatus == 4) {
    //     arr.push(that.data.all[i]);
    //   }
    // }
    // for(var i = 0; i < that.data.all.length; i++){
    //   if(that.data.all[i].orderStatus == 4) {
    //     var nestedArray = that.data.all[i];
    //     var nestedArr = [];
    //     nestedArr.push(nestedArray);
    //     arr.push(nestedArr);
    //   }
    // }
    for (var i = 0; i < that.data.all.length; i++) {
      if (that.data.all[i].orderStatus == 4) {
        var identity = that.data.all[i].identity; // 假设 identity 是用来标识对象的唯一值
        if (!identityMap[identity]) {
          var nestedArray = that.data.all[i];
          var nestedArr = [];
          nestedArr.push(nestedArray);
          arr.push(nestedArr);
          identityMap[identity] = arr.length - 1; // 将 identity 值与索引关联起来
        } else {
          // 如果已经存在相同 identity 值的数组，则直接将对象添加到对应的数组中
          arr[identityMap[identity]].push(that.data.all[i]);
        }
      }
    }
    console.log("已完成的订单")
    console.log(arr)
    this.setData({
      list: arr,
      selectedIndex: 4,
      orderStatus: 4,
    })

    if (this.data.list.length == 0) {
      that.setData({
        goodsstat: true
      })
    } else {
      that.setData({
        goodsstat: false,
      })
    }
  },


  getstat: function () {
    // 更新订单列表数据
    console.log(this.data.orderStatus)
    if (this.data.orderStatus == 1) {
      this.payment();
    } else if (this.data.orderStatus == 2) {
      this.shipments();
    } else if (this.data.orderStatus == 3) {
      this.receipt();
    } else if (this.data.orderStatus == 4) {
      this.ovre();
    } else {
      this.quanbu();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取跳转时传入的状态参数
    let orderStatus = parseInt(options.orderStatus);
    console.log(orderStatus);
    // this.startInter();
    this.setData({
      orderStatus: orderStatus
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getorder();

    // this.startInter();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})